package com.nq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nq.common.ServerResponse;
import com.nq.dao.StPremarketStockMapper;
import com.nq.dao.stock.StStockMapper;
import com.nq.pojo.SiteSetting;
import com.nq.pojo.StLimitUpStock;
import com.nq.pojo.StPremarketStock;
import com.nq.pojo.vo.StPremarketStockVo;
import com.nq.service.ISiteSettingService;
import com.nq.service.IStPremarketStockService;
import com.nq.stock.entity.StStock;
import com.nq.utils.DateTimeUtil;
import com.nq.utils.SymmetricCryptoUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Service
public class StPremarketStockServiceImpl extends ServiceImpl<StPremarketStockMapper, StPremarketStock>
        implements IStPremarketStockService {

    @Resource
    private StPremarketStockMapper stPremarketStockMapper;
    @Autowired
    private StStockMapper stockMapper;
    @Autowired
    private ISiteSettingService iSiteSettingService;
    @Value("${spring.profiles.active}")
    private String active;

    /**
     * 根据股票编码和交易所获取盘前配置
     * @param stockCode
     * @param market
     * @return
     */
    @Override
    public List<StPremarketStock> listByCodeAndMarket(String stockCode, String market){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(StringUtils.isNotBlank(stockCode),"stock_code", stockCode);
        queryWrapper.eq(StringUtils.isNotBlank(market), "market", market);
        queryWrapper.orderByDesc("add_time");
        List<StPremarketStock> list = stPremarketStockMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public ServerResponse getPremarketStock(int pageNum, int pageSize, String stockCode, String market) {
        Page<StPremarketStock> page = PageHelper.startPage(pageNum, pageSize);

        List<StPremarketStock> list = listByCodeAndMarket(stockCode, market);

        PageInfo<StPremarketStock> pageInfo = new PageInfo<>(page);
        pageInfo.setList(list);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse addPremarketStock(String market, String stockCode,
                                            String startTime, String endTime,
                                            String beforeStartTime, String beforeEndTime,
                                            String price, String maxPrice,
                                            String sellMinPrice, String sellMaxPrice, Integer times) {

        if (StringUtils.isBlank(market)) {
            return ServerResponse.createByErrorMsg("参数错误【market】");
        }
        if (StringUtils.isBlank(stockCode)) {
            return ServerResponse.createByErrorMsg("参数错误【stockCode】");
        }

        QueryWrapper<StStock> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", stockCode);
            queryWrapper.eq("market", market);
        StStock stock = stockMapper.selectOne(queryWrapper);

        if (stock == null){
            return ServerResponse.createByErrorMsg("股票不存在！");
        }

        String transAmBeginUs = "";
        String transPmEndUs = "";
                // 判断盘前1 开市期 盘前2 的时间不重叠
        SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting();
        if (null != siteSetting) {
            // 美股上午开市时间
            transAmBeginUs = siteSetting.getTransAmBeginUs();
            // 美股下午闭市时间
            transPmEndUs = siteSetting.getTransPmEndUs();

        }

        StPremarketStock premarketStock = new StPremarketStock();
        premarketStock.setStockName(stock.getName());
        premarketStock.setStockCode(stockCode);
        premarketStock.setMarket(market);
        premarketStock.setPrice(new BigDecimal(price));
        premarketStock.setTimes(times);
        premarketStock.setMaxPrice(new BigDecimal(maxPrice));
        premarketStock.setSellMinPrice(new BigDecimal(sellMinPrice));
        premarketStock.setSellMaxPrice(new BigDecimal(sellMaxPrice));
        premarketStock.setAddTime(new Date());
        // 设置时区 - 因为美国3月11日到11月7日处于夏令时，是GMT-4 其余时间是GMT-5
        premarketStock.setStartTime(DateTimeUtil.strToDate(startTime));
        premarketStock.setEndTime(DateTimeUtil.strToDate(endTime));

        if (!StringUtils.isEmpty(transAmBeginUs) && !StringUtils.isEmpty(transPmEndUs)){
            String startH = DateTimeUtil.dateToStr(DateTimeUtil.strToDate(startTime), "HH:mm");
            String endH = DateTimeUtil.dateToStr(DateTimeUtil.strToDate(endTime), "HH:mm");


            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");

            LocalTime transAmBegin = LocalTime.parse(transAmBeginUs, formatter);
            LocalTime transPmEnd = LocalTime.parse(transPmEndUs, formatter);
            LocalTime startP = LocalTime.parse(startH, formatter);
            LocalTime endP = LocalTime.parse(endH, formatter);

            boolean isOverlap = (startP.isBefore(transPmEnd) && endP.isAfter(transAmBegin));
//            if (!isOverlap) {
//                return ServerResponse.createByErrorMsg("盘前交易2与开市时间冲突, 请核实!");
//            }

        }


        Date beforeStart = DateTimeUtil.strToDate(beforeStartTime);
        Date beforeEnd = DateTimeUtil.strToDate(beforeEndTime);
        premarketStock.setBeforeStartTime(beforeStart);
        premarketStock.setBeforeEndTime(beforeEnd);
        if (!StringUtils.isEmpty(transAmBeginUs) && !StringUtils.isEmpty(transPmEndUs)){
            String startH = DateTimeUtil.dateToStr(beforeStart, "HH:mm");
            String endH = DateTimeUtil.dateToStr(beforeEnd, "HH:mm");


            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");

            LocalTime transAmBegin = LocalTime.parse(transAmBeginUs, formatter);
            LocalTime transPmEnd = LocalTime.parse(transPmEndUs, formatter);
            LocalTime startP = LocalTime.parse(startH, formatter);
            LocalTime endP = LocalTime.parse(endH, formatter);

            boolean isOverlap = (startP.isBefore(transPmEnd) && endP.isAfter(transAmBegin));
//            if (!isOverlap) {
//                return ServerResponse.createByErrorMsg("盘前交易1与开市时间冲突, 请核实!");
//            }

        }

        stPremarketStockMapper.insert(premarketStock);
        return ServerResponse.createBySuccess("操作成功！");
    }

    @Override
    public ServerResponse deletePremarketStock(String id) {
        return stPremarketStockMapper.deleteById(id) > 0 ? ServerResponse.createBySuccessMsg("删除成功！") : ServerResponse.createByErrorMsg("删除失败！");
    }

    @Override
    public ServerResponse updatePremarketStock(StPremarketStockVo model) {

        String transAmBeginUs = "";
        String transPmEndUs = "";
        // 判断盘前1 开市期 盘前2 的时间不重叠
        SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting();
        if (null != siteSetting) {
            // 美股上午开市时间
            transAmBeginUs = siteSetting.getTransAmBeginUs();
            // 美股下午闭市时间
            transPmEndUs = siteSetting.getTransPmEndUs();

        }

        StPremarketStock premarketStock = new StPremarketStock();
        premarketStock.setId(model.getId());
        premarketStock.setPrice(model.getPrice());
        premarketStock.setMaxPrice(model.getMaxPrice());
        premarketStock.setSellMinPrice(model.getSellMinPrice());
        premarketStock.setSellMaxPrice(model.getSellMaxPrice());
        premarketStock.setTimes(model.getTimes());

        // 设置时区 - 因为美国3月11日到11月7日处于夏令时，是GMT-4 其余时间是GMT-5
        Date start = DateTimeUtil.strToDate(model.getStartTime());
        Date end = DateTimeUtil.strToDate(model.getEndTime());
        premarketStock.setStartTime(start);
        premarketStock.setEndTime(end);

        if (!StringUtils.isEmpty(transAmBeginUs) && !StringUtils.isEmpty(transPmEndUs)){
            String startH = DateTimeUtil.dateToStr(start, "HH:mm");
            String endH = DateTimeUtil.dateToStr(end, "HH:mm");


            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");

            LocalTime transAmBegin = LocalTime.parse(transAmBeginUs, formatter);
            LocalTime transPmEnd = LocalTime.parse(transPmEndUs, formatter);
            LocalTime startP = LocalTime.parse(startH, formatter);
            LocalTime endP = LocalTime.parse(endH, formatter);

            boolean isOverlap = (startP.isBefore(transPmEnd) && startP.isAfter(transAmBegin)) && (endP.isBefore(transPmEnd) && endP.isAfter(transAmBegin));
//            if (!isOverlap) {
//                return ServerResponse.createByErrorMsg("盘前交易2与开市时间冲突, 请核实!");
//            }

        }

        Date beforeStart = DateTimeUtil.strToDate(model.getBeforeStartTime());
        Date beforeEnd = DateTimeUtil.strToDate(model.getBeforeEndTime());
        premarketStock.setBeforeStartTime(beforeStart);
        premarketStock.setBeforeEndTime(beforeEnd);

        if (!StringUtils.isEmpty(transAmBeginUs) && !StringUtils.isEmpty(transPmEndUs)){
            String startH = DateTimeUtil.dateToStr(beforeStart, "HH:mm");
            String endH = DateTimeUtil.dateToStr(beforeEnd, "HH:mm");


            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");

            LocalTime transAmBegin = LocalTime.parse(transAmBeginUs, formatter);
            LocalTime transPmEnd = LocalTime.parse(transPmEndUs, formatter);
            LocalTime startP = LocalTime.parse(startH, formatter);
            LocalTime endP = LocalTime.parse(endH, formatter);

            boolean isOverlap = (startP.isBefore(transPmEnd) && startP.isAfter(transAmBegin)) && (endP.isBefore(transPmEnd) && endP.isAfter(transAmBegin));
//            if (!isOverlap) {
//                return ServerResponse.createByErrorMsg("盘前交易1与开市时间冲突, 请核实!");
//            }

        }

        return stPremarketStockMapper.updateById(premarketStock) > 0 ? ServerResponse.createBySuccessMsg("更新成功！") : ServerResponse.createByErrorMsg("更新失败！");
    }

}
